#pragma once

#include <Windows.h>
#include <map>
#include "Singleton.h"

class CThread;
class CThreadManager : public Singleton<CThreadManager>
{
public:
    CThreadManager()
    {
        InitializeCriticalSection(&cs);
    }
    ~CThreadManager()
    {
        DeleteCriticalSection(&cs);
    }
public:
    bool registThread(unsigned id, CThread* p)
    {
        if( p == NULL )
        {   
            // abnormal instance
            return false;            
        }

        if( m_mapThread.find(id) != m_mapThread.end() )
        {
            // alread registed id
            return false;
        }

        EnterCriticalSection(&cs);
        m_mapThread.insert(std::pair<unsigned, CThread*>(id, p));
        LeaveCriticalSection(&cs);

        return true;
    }
    bool unregistThread(const unsigned& id)
    {
        //std::map<unsigned, CThread*>::iterator iter = m_mapThread.find(id);
        auto iter = m_mapThread.find(id);
        if( iter == m_mapThread.end() )
        {
            // unregisted id
            return false;
        }

        EnterCriticalSection(&cs);
        m_mapThread.erase(iter);
        LeaveCriticalSection(&cs);

        return true;
    }
public:
    CThread* getThread(const unsigned& id)
    {
        //std::map<unsigned, CThread*>::iterator iter = m_mapThread.find(id);
        auto iter = m_mapThread.find(id);
        if( iter == m_mapThread.end() )
        {
            // unregisted id
            return NULL;
        }

        return iter->second;
    }
private:
    std::map<unsigned, CThread*> m_mapThread;
    CRITICAL_SECTION cs;
};